const path = require('path')
const { name } = require('./package')
const fs = require('fs')
const shell = require('shelljs')
const webpack = require('webpack')

const ROOT_PATH = path.resolve(__dirname)
const ROOT_TOP_PATH = path.resolve(ROOT_PATH)
const IS_PRO = process.env.NODE_ENV === 'production' // 是否是生产环境

console.log(process.argv)

const lintOnSave = !IS_PRO // 是否开启eslint

const argvList = process.argv
let defineGlobalVars = {}
if (Array.isArray(argvList)) {
  defineGlobalVars = argvList.reduce((pre, cur) => {
    const splitArr = cur.split('=')
    const [key, value] = splitArr
    if (splitArr?.length && /^--/.test(key)) {
      const name = key.replace('--', '')
      pre[name] = JSON.stringify(value)
      pre[name.toLocaleLowerCase()] = JSON.stringify(value)
    }
    return pre
  }, {})
}

if (!IS_PRO) {
  // 开发环境
  const huskyPath = path.join(ROOT_TOP_PATH, '.husky')
  console.log('ROOT_TOP_PATH', ROOT_TOP_PATH)
  if (!fs.existsSync(path.join(huskyPath, '_/husky.sh')) || !fs.existsSync(path.join(huskyPath, 'pre-commit'))) {
    // 不存在husky
    fs.existsSync(huskyPath) && fs.rmdirSync(huskyPath, { recursive: true })
    shell.cd(ROOT_TOP_PATH)
    if (shell.exec('npx husky install && npx husky add .husky/pre-commit "npx lint-staged"').code !== 0) {
      shell.exit(1)
    }
    shell.cd(ROOT_PATH)
  }
}

const port = 3033 // 这里调整

module.exports = {
  publicPath: '',
  lintOnSave,
  outputDir: 'dist',
  css: {
    requireModuleExtension: true,
    loaderOptions: {
      scss: {
        // @/ 是 src/ 的别名
      }
    }
  },
  // 第三方插件配置
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: []
    }
  },
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@root', ROOT_PATH)
      .set('@', path.join(ROOT_PATH, 'src'))
      .set('~@', path.join(ROOT_PATH, 'src'))
      .set('@mxui', path.join(ROOT_PATH, '.mxui'))
    config.devtool(IS_PRO ? 'none' : 'eval-cheap-module-source-map')

    config.plugin('defineArgs').use(webpack.DefinePlugin, [{ ...defineGlobalVars }])

    // 指定eslint
    if (lintOnSave) {
      config.module
        .rule('eslint')
        .use('eslint-loader')
        .tap((options) => {
          const eslintPath = path.join(ROOT_PATH, 'node_modules/eslint')
          const configFile = path.join(ROOT_PATH, '.eslintrc.js')
          if (options && fs.existsSync(eslintPath)) {
            options.eslintPath = eslintPath
            options.configFile = configFile
            options.cache = false
          }
          return options
        })
    }
  },
  configureWebpack: {
    output: {
      library: `${name}-[name]`,
      libraryTarget: 'umd', // 把微应用打包成 umd 库格式
      jsonpFunction: `webpackJsonp_${name}`
    },
    module: {
      rules: [
        {
          test: /\.mjs$/,
          include: /node_modules/,
          type: 'javascript/auto'
        }
      ]
    },
    devServer: {
      overlay: {
        warnings: false,
        errors: false
      },
      open: true,
      port,
      headers: {
        'Access-Control-Allow-Origin': '*'
      }
    }
  }
}
